package service

import (
	"fmt"
	"study/testproject/source/db/sql/mysql"
)

func InitMessage(uid int, receiveuid string) string {
	db, err := mysql.GetDBConn()
	defer db.Close()
	if err != nil {
		errorPrint(err)
	}
	id := fmt.Sprintf("%d", uid)
	sql := "select * from v_message_desc where (senduid='" + receiveuid + "' and receiveuid='" + id + "') or (senduid='" + id + "' and receiveuid='" + receiveuid + "') order by mtime asc"
	list := mysql.GetBySqlToListMap(sql)
	json := mysql.ToJson(list)
	return json
}
func GetMessage(uid int, receiveuid string) string {
	db, err := mysql.GetDBConn()
	defer db.Close()
	if err != nil {
		errorPrint(err)
	}
	id := fmt.Sprintf("%d", uid)
	sql := "select mid,senduid,receiveuid,mcontent,mtime,mstatus from message where senduid='" + receiveuid + "' and receiveuid='" + id + "' and mstatus=0 order by mtime asc"

	list := mysql.GetBySqlToListMap(sql)
	if list.Size() > 0 {
		json := mysql.ToJson(list)
		UpdateMessageStatus(uid, receiveuid)
		return json
	}
	return ""
}

//将发送的消息存放到数据表中
func SendMessage(sendUid, receiveUid, mstatus int, time, content string) (row int, err error) {
	fmt.Println("send=", sendUid, receiveUid, content)
	db, err := mysql.GetDBConn()
	defer db.Close()
	if err != nil {
		errorPrint(err)
	}
	var sql string = "INSERT INTO message(senduid,receiveuid,mcontent,mtime,mstatus)values(?,?,?,?,?)"
	row, err = mysql.Exec(sql, sendUid, receiveUid, content, time, mstatus)
	return row, err
}

//读取完消息修改状态
func UpdateMessageStatus(uid int, receiveuid string) {
	db, err := mysql.GetDBConn()
	defer db.Close()
	if err != nil {
		errorPrint(err)
	}
	var sql string = "update message set mstatus=1 where receiveuid=? and senduid=? and mstatus=0"
	mysql.Exec(sql, uid, receiveuid)
}
